package com.distribution.common.web.auth;

import com.distribution.repository.dao.AccountUserDao;
import com.distribution.repository.dao.OperationDao;
import com.distribution.repository.dao.RoleDao;
import com.distribution.repository.entity.AccountUser;
import com.distribution.repository.entity.AccountUserRole;
import com.distribution.repository.entity.Operation;
import com.distribution.repository.entity.Role;
import com.distribution.common.web.auth.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @author test
 * @date 2022年01月04日 14:24
 */

@Service
public class LoginService {

    @Autowired
    private AccountUserDao accountUserDao;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private OperationDao operationDao;

    public SecurityUser loadByUsername(String username) {
        AccountUser user = accountUserDao.getUserByName(username);

        if (Objects.nonNull(user)) {
            SecurityUser securityUser = new SecurityUser();
            securityUser.setUsername(username);
            //todo 此处为了方便，直接在数据库存储的明文，实际生产中应该存储密文，则这里不用再次加密
            securityUser.setPassword(passwordEncoder.encode(user.getPassword()));
            //查询该用户的角色
            List<AccountUserRole> userRoles = accountUserDao.getAccountUserRoleList(user.getAccountUserId());
            //获取权限集合
            Collection<? extends GrantedAuthority> authorities = merge(userRoles);
            securityUser.setAuthorities(authorities);
            return securityUser;
        }
        return null;
    }

    private Collection<? extends GrantedAuthority> merge(List<AccountUserRole> userRoles) {
        List<String> roles = listRoles(userRoles);
        List<String> auths = listAuths(userRoles);
        roles.addAll(auths);
        return AuthorityUtils.createAuthorityList(roles.toArray(new String[0]));
    }

    /**
     * 查询角色
     */
    private List<String> listRoles(List<AccountUserRole> userRoles) {
        List<String> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(userRoles)) {

            for (AccountUserRole item : userRoles) {
                Role role = roleDao.getRoleById(item.getRoleId());
                if (Objects.nonNull(role)) {
                    list.add(role.getRoleName());
                }
            }
        }
        return list;
    }

    private List<String> listAuths(List<AccountUserRole> userRoles) {
        List<String> list = new ArrayList<>();
        if (userRoles == null || CollectionUtils.isEmpty(userRoles)) {
            return list;
        }


        for (AccountUserRole item : userRoles) {
            List<Operation> operationList = operationDao.getOperationByRoleId(item.getRoleId());

            if (Objects.nonNull(operationList) || operationList.isEmpty()) {
                continue;
            }

            for (Operation operation : operationList) {
                if (operation.getOperationUrl() != null) {
                    list.add(operation.getOperationUrl());
                }
            }
        }

        return list;
    }

}
